/*
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */
package gui;

import interfaces.EditPanel;

import java.awt.Dimension;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.swing.BoxLayout;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;

import org.apache.log4j.Logger;

import output.OutputTypeEnum;
import tools.InputType;
import tools.StringTools;
import database.DBConnectionFactory;

/**
 * Settings panel for commands
 * 
 * 
 */
public class CommandsPanel extends JPanel implements EditPanel {
   private static final long serialVersionUID = 4228896307757033356L;
   private JTextField name;
   private JTextField aliases;
   private JTextField priority;
   private JTextField classname;
   private JTextField classurl;
   private JTextArea syntax;
   private JTextArea help;
   private JTextField cmdtype;
   private JCheckBox bypassAntiSpam;
   private JCheckBox publicAccess;
   private JComboBox delivery;
   private String itemName;
   private final DialogPanel parent;

   public CommandsPanel(final DialogPanel parent) {
	  super();
	  this.parent = parent;
	  initialize();
   }

   @Override
   public final void checkInputs() {
	  if (name.getText().equals("") || !StringTools.validateInput(InputType.INT, priority.getText())
			|| classname.getText().equals("") || classurl.getText().equals("") || syntax.getText().equals("")
			|| help.getText().equals("") || cmdtype.getText().equals("")) {
		 parent.setSaveButtonEnabled(false);
	  } else {
		 parent.setSaveButtonEnabled(true);
	  }
   }

   @Override
   public boolean delete() {
	  if (name.getText().equals(""))
		 return false;
	  PreparedStatement ps = null;
	  boolean success = false;
	  try {
		 ps = DBConnectionFactory.getConnectionHandler().getConnection().prepareStatement("DELETE FROM commands WHERE name = ?");
		 ps.setString(1, itemName);
		 ps.executeUpdate();
		 success = true;
	  } catch (final SQLException e) {
		 Logger.getLogger("Error").error("", e);
	  } finally {
		 try {
			ps.close();
		 } catch (final Exception e) {
		 }
	  }
	  return success;
   }

   @Override
   public String getItemName() {
	  return itemName;
   }

   /**
    * Initializes the components
    */
   private void initialize() {
	  setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
	  name = new JTextField();
	  name.setPreferredSize(new Dimension(300, 20));
	  name.getDocument().addDocumentListener(new MyDocumentListener(this));
	  aliases = new JTextField();
	  aliases.setPreferredSize(new Dimension(300, 20));
	  aliases.getDocument().addDocumentListener(new MyDocumentListener(this));
	  priority = new JTextField();
	  priority.setPreferredSize(new Dimension(300, 20));
	  priority.getDocument().addDocumentListener(new MyDocumentListener(this));
	  classname = new JTextField();
	  classname.setPreferredSize(new Dimension(300, 20));
	  classname.getDocument().addDocumentListener(new MyDocumentListener(this));
	  classurl = new JTextField();
	  classurl.setPreferredSize(new Dimension(300, 20));
	  classurl.getDocument().addDocumentListener(new MyDocumentListener(this));
	  syntax = new JTextArea();
	  syntax.setRows(5);
	  syntax.setPreferredSize(new Dimension(300, 20));
	  syntax.setLineWrap(true);
	  syntax.getDocument().addDocumentListener(new MyDocumentListener(this));
	  help = new JTextArea();
	  help.setRows(5);
	  help.setLineWrap(true);
	  help.setPreferredSize(new Dimension(300, 20));
	  help.getDocument().addDocumentListener(new MyDocumentListener(this));
	  cmdtype = new JTextField();
	  cmdtype.setPreferredSize(new Dimension(300, 20));
	  cmdtype.getDocument().addDocumentListener(new MyDocumentListener(this));
	  bypassAntiSpam = new JCheckBox("Select for yes");
	  bypassAntiSpam.setPreferredSize(new Dimension(300, 20));
	  bypassAntiSpam.addChangeListener(new javax.swing.event.ChangeListener() {
		 @Override
		 public void stateChanged(final javax.swing.event.ChangeEvent e) {
			checkInputs();
		 }
	  });
	  publicAccess = new JCheckBox("Select for yes");
	  publicAccess.setPreferredSize(new Dimension(300, 20));
	  publicAccess.addChangeListener(new javax.swing.event.ChangeListener() {
		 @Override
		 public void stateChanged(final javax.swing.event.ChangeEvent e) {
			checkInputs();
		 }
	  });

	  String[] list = new String[OutputTypeEnum.values().length];
	  int i = 0;
	  for (OutputTypeEnum ote : OutputTypeEnum.values()) {
		 list[i] = ote.toString();
		 ++i;
	  }
	  delivery = new JComboBox(list);
	  delivery.setEditable(false);

	  this.add(new CustomPanel(new CustomLabel("Name", 150, 20), name));
	  this.add(new CustomPanel(new CustomLabel("Aliases (sep with ,)", 150, 20), aliases));
	  this.add(new CustomPanel(new CustomLabel("Priority", 150, 20), priority));
	  this.add(new CustomPanel(new CustomLabel("Class Name", 150, 20), classname));
	  this.add(new CustomPanel(new CustomLabel("Class URL", 150, 20), classurl));
	  this.add(new CustomPanel(new CustomLabel("Syntax", 150, 20), syntax));
	  this.add(new CustomPanel(new CustomLabel("Help", 150, 20), help));
	  this.add(new CustomPanel(new CustomLabel("Command Type", 150, 20), cmdtype));
	  this.add(new CustomPanel(new CustomLabel("Bypass Anti Spam", 150, 20), bypassAntiSpam));
	  this.add(new CustomPanel(new CustomLabel("Public Access Command", 150, 20), publicAccess));
	  this.add(new CustomPanel(new CustomLabel("Output Delivery", 150, 20), delivery));
   }

   @Override
   public JPanel load(final String item) {
	  itemName = item;
	  removeAll();
	  validate();
	  initialize();
	  PreparedStatement ps = null;
	  ResultSet rs = null;
	  try {
		 ps = DBConnectionFactory.getConnectionHandler().getConnection()
			   .prepareStatement("SELECT * FROM commands WHERE name = ?");
		 ps.setString(1, item);
		 rs = ps.executeQuery();

		 if (rs.next()) {
			name.setText(rs.getString("name"));
			aliases.setText(rs.getString("aliases"));
			priority.setText(String.valueOf(rs.getInt("priority")));
			classname.setText(rs.getString("classname"));
			classurl.setText(rs.getString("classurl"));
			syntax.setText(rs.getString("syntax"));
			help.setText(rs.getString("help"));
			cmdtype.setText(rs.getString("cmdtype"));
			bypassAntiSpam.setSelected(rs.getBoolean("bypassantispam"));
			publicAccess.setSelected(rs.getBoolean("publicaccess"));
			delivery.setSelectedItem(rs.getString("delivery"));
		 } else {
			name.setText(item);
		 }
	  } catch (final SQLException e) {
		 Logger.getLogger("Error").error("", e);
	  } finally {
		 try {
			rs.close();
		 } catch (final Exception e) {
		 }
		 try {
			ps.close();
		 } catch (final Exception e) {
		 }
	  }
	  return this;
   }

   @Override
   public boolean save() {
	  if (name.getText().equals("") || !StringTools.validateInput(InputType.INT, priority.getText())
			|| classname.getText().equals("") || classurl.getText().equals("") || syntax.getText().equals("")
			|| help.getText().equals("") || cmdtype.getText().equals(""))
		 return false;
	  PreparedStatement ps = null;
	  ResultSet rs = null;
	  boolean success = false;
	  try {
		 ps = DBConnectionFactory.getConnectionHandler().getConnection()
			   .prepareStatement("SELECT * FROM commands WHERE name = ?");
		 ps.setString(1, itemName);
		 rs = ps.executeQuery();

		 if (rs.next()) {
			try {
			   ps.close();
			} catch (final Exception e) {
			}

			ps = DBConnectionFactory
				  .getConnectionHandler()
				  .getConnection()
				  .prepareStatement(
						"UPDATE commands SET name = ?," + "aliases = ?,priority = ?,"
							  + "classname = ?,classurl = ?, syntax = ?,help = ?, cmdtype = ?, bypassantispam = ?, "
							  + "publicaccess = ?, delivery = ? WHERE name = ?");
			ps.setString(1, name.getText());
			ps.setString(2, aliases.getText());
			ps.setInt(3, Integer.parseInt(priority.getText()));
			ps.setString(4, classname.getText());
			ps.setString(5, classurl.getText());
			ps.setString(6, syntax.getText());
			ps.setString(7, help.getText());
			ps.setString(8, cmdtype.getText());
			ps.setBoolean(9, bypassAntiSpam.isSelected());
			ps.setBoolean(10, publicAccess.isSelected());
			ps.setString(11, delivery.getSelectedItem().toString());
			ps.setString(12, itemName);
			ps.executeUpdate();
		 } else {
			try {
			   ps.close();
			} catch (final Exception e) {
			}

			ps = DBConnectionFactory.getConnectionHandler().getConnection()
				  .prepareStatement("INSERT INTO commands " + "VALUES(?,?,?,?,?,?,?,?,?,?,?)");
			ps.setString(1, name.getText());
			ps.setString(2, aliases.getText());
			ps.setInt(3, Integer.parseInt(priority.getText()));
			ps.setString(4, classname.getText());
			ps.setString(5, classurl.getText());
			ps.setString(6, syntax.getText());
			ps.setString(7, help.getText());
			ps.setString(8, cmdtype.getText());
			ps.setBoolean(9, bypassAntiSpam.isSelected());
			ps.setBoolean(10, publicAccess.isSelected());
			ps.setString(11, delivery.getSelectedItem().toString());
			ps.executeUpdate();
		 }
		 itemName = name.getText();
		 success = true;
	  } catch (final SQLException e) {
		 Logger.getLogger("Error").error("", e);
	  } finally {
		 try {
			rs.close();
		 } catch (final Exception e) {
		 }
		 try {
			ps.close();
		 } catch (final Exception e) {
		 }
	  }
	  return success;
   }
}
